﻿using DomainModelStructure;
using DomainModelStructure.Tools;
using EntAppFrameWork;
using EntAppFrameWork.DataAccess;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuildRWSView
{
    public class FixViewLoad : DMSStructLoad
    {
        protected override DMStrucBuilder SetDMStrucBuilder()
        {
            return new FixView();
        }
    }

    public class FixView : DMStrucBuilder
    {


        protected override OneToManyHiddenRelation SetOnetToManyHiddenRelation()
        {
            return new OTMHRView();
        }

    }
    public class OTMHRView : OneToManyHiddenRelation
    {
        public override void Action(Object context)
        {
            IDataAccess idaWrite = EntAppFrameWork.EntAppFrameWorkContext.DataAccess.CreateDataAccess("MSDAWrite");
            EntAppFrameWork.DomainModel.Attribute.ColumnAttribute columnAttribute = null;
            EntAppFrameWork.DomainModel.Attribute.HiddenRelationAttribute hiddenRelationAttribute = null;
            ClassUtility.GetAttribute(this.CurrentPropertyInfo, out columnAttribute, out hiddenRelationAttribute);
            String hiddenTable = BuildTableByGrade(hiddenRelationAttribute.Table);
            String readDB = ConfigurationManager.AppSettings["readDB"].ToString();
            //判断视图是否已存在，存在则删除
            String sql = @"IF EXISTS(SELECT 1 FROM sys.views WHERE name='View_" + hiddenTable + @"')
                            BEGIN
                              drop view View_" + hiddenTable + @"
                            END";
            EFC.DataAccess.DataAccess.ExecuteNonQuery(sql);

            //创建视图
            sql = @"create view View_" + hiddenTable + " as " + @"SELECT   dbo." + hiddenTable + @".*
                        FROM      dbo." + hiddenTable + @"

                        UNION
                        SELECT   *
                        FROM      " + readDB + @".dbo." + hiddenTable + @"
                        WHERE   " + readDB + @".dbo." + hiddenTable + @"." + hiddenRelationAttribute.SourceColumnID + @" NOT IN
                                            (SELECT   " + hiddenRelationAttribute.SourceColumnID + @"
                                             FROM      dbo." + hiddenTable + ")";
            EFC.DataAccess.DataAccess.ExecuteNonQuery(sql);

            base.Action(context);
        }
    }

}
